<template>
	<view class="page-content">
		<NavBar :isRight="true" :isLeft="true" :ricon="'more-filled'"
			:bgcolor="isNavBackgroundStyle?'rgba(255,255,255,1)':''" @onLeft="back" @onRight="handleRightNavClick"
			class="nav-bar">
		</NavBar>
		<view v-if="isLoading" style="padding: 20px; text-align: center;">
			<text>加载中...</text>
		</view>
		<!-- 注意：UserInfo 组件可能需要一个 prop 来显示备注名，或者其内部逻辑需要调整 -->
		<UserInfo v-if="!isLoading && userInfoItem && userInfoItem.userId" :userInfo="currentDisplayUserInfo"
			:isFollowed="isFollowed" :showOther="true" :postList="postList" :tagList="userInfoItem.topicsList"
			:storeList="storeList" @onRemark="showRemarkModal = true" @onFollow="onFollow"></UserInfo>
		<view v-if="!isLoading && (!userInfoItem || !userInfoItem.userId)" style="padding: 20px; text-align: center;">
			<text>用户信息加载失败或用户不存在</text>
		</view>

		<!-- 设置备注的弹窗 -->
		<u-modal :show="showRemarkModal" title="设置备注" showCancelButton @confirm="confirmRemark" @cancel="cancelRemark"
			confirmColor="#ff9900">
			<view style="padding: 20rpx;">
				<u-input placeholder="请输入备注名" border="surround" v-model="inputRemark" clearable></u-input>
			</view>
		</u-modal>

		<!-- 右上角操作表 -->
		<u-action-sheet :actions="actions" :show="showActionsSheet" cancelText="取消" @select="handleActionSelect"
			@close="showActionsSheet = false"></u-action-sheet>
	</view>
</template>

<script>
	import UserInfo from "@/components/user-info/user-info.vue"
	import NavBar from "@/components/common-nav/common-nav.vue"
	import {
		getUser,
		getOwnPosts,
		getClientFollow,
		setFriendRemark
	} from '@/request/api.js' // 确保导入了 setFriendRemark

	export default {
		components: {
			UserInfo,
			NavBar
		},
		data() {
			return {
				isLoading: true,
				userId: null,
				userInfoItem: {}, // 从服务器获取的原始用户信息
				postList: [],
				storeList: [],
				isFollowed: false,
				eventChannel: null,
				isNavBackgroundStyle: false,

				showRemarkModal: false, // 控制备注弹窗的显示
				inputRemark: '', // 备注输入框的值
				currentRemark: '', // 当前已设置的备注名，用于回显和比较

				showActionsSheet: false, // 控制右上角操作表的显示
				actions: [{
						name: '设置备注'
					},
					// 可以添加其他操作，例如：举报、拉黑等
				]
			}
		},
		computed: {
			// 计算属性，用于决定最终显示的用户名称
			// 如果有备注名，优先显示备注名，否则显示昵称
			currentDisplayUserInfo() {
				if (!this.userInfoItem) return {};
				return {
					...this.userInfoItem,
					nickName: this.currentRemark || this.userInfoItem.nickName // 优先显示备注
				};
			}
		},
		onLoad(option) {
			this.eventChannel = this.getOpenerEventChannel();
			let initialUserId = null;
			let initialIsFollowed = false;
			let initialRemark = ''; // 初始化备注

			if (this.eventChannel && this.eventChannel.on && !option.userId) {
				this.eventChannel.on('sendInitData', (res) => {
					let data = JSON.parse(res.data);
					initialUserId = data.userId;
					initialIsFollowed = data.isFollowed || false;
					initialRemark = data.remark || ''; // 从父页面接收备注
					this.initializePage(initialUserId, initialIsFollowed, initialRemark);
				});
			} else if (option.userId) {
				initialUserId = option.userId;
				// 如果直接通过 option 传递关注状态和备注
				initialIsFollowed = option.isFollowed === 'true' || option.isFollowed === true;
				initialRemark = option.remark || '';
				this.initializePage(initialUserId, initialIsFollowed, initialRemark);
			} else {
				uni.showToast({
					title: '无效的用户ID',
					icon: 'error'
				});
				uni.navigateBack();
			}
		},
		onPageScroll(e) {
			const scrollTop = e.scrollTop;
			this.isNavBackgroundStyle = scrollTop > 10 ? true : false;


		},
		methods: {
			initializePage(userId, isFollowed, remark) {
				this.userId = userId;
				this.isFollowed = isFollowed;
				this.currentRemark = remark; // 设置初始备注
				this.inputRemark = remark; // 备注输入框也同步初始值
				this.getOtherUserInfo();
				this.getPostInfo();
			},
			back() {
				uni.navigateBack()
			},
			getPostInfo() {
				// ... (您的 getPostInfo 方法保持不变)
				let params = {
					userId: this.userId,
					pageNum: 1,
					pageSize: 10,
					fellowsIds: []
				}
				getOwnPosts(params).then((res) => {
					if (res.data && res.data.rows) {
						let list = res.data.rows.filter(subArr => subArr.files && subArr.files.length > 0 && subArr
							.files[0] && subArr.files[0].fileType == 'image/jpeg')
						this.postList = list.slice(0, 4).map(subArr => {
							return {
								image: subArr.files[0].fileUrl
							}
						})
					} else {
						this.postList = [];
					}
				})
			},
			getOtherUserInfo() {
				this.isLoading = true;
				getUser(this.userId).then((res) => {
					if (res.data && res.data.data) {
						this.userInfoItem = res.data.data;
						// 如果API返回了备注，则更新 currentRemark
						this.currentRemark = this.userInfoItem.remarkName || this.currentRemark || this
							.userInfoItem.nickName; // 假设后端返回的备注字段是 remarkName
						this.inputRemark = this.currentRemark; // 同步到输入框
						// isFollowed 状态通常由父页面或这里API返回的 isFollowed 字段决定
						this.isFollowed = this.userInfoItem.isFollowed > 0 ? true : false;
					} else {
						this.userInfoItem = {};
					}
				}).catch(err => {
					this.userInfoItem = {};
				}).finally(() => {
					this.isLoading = false;
				});
			},
			onFollow(e) {
				getClientFollow({
					userId: this.userInfoItem.userId
				}).then(res => {
					if (res.data && res.data.code === 200) {
						this.isFollowed = !this.isFollowed;
						if (this.eventChannel) {
							this.eventChannel.emit('returnData', {
								userId: this.userId,
								type: 4, // 自定义类型，表示关注状态变更
								isFollowed: this.isFollowed,
								remark: this.currentRemark // 关注状态变化时也回传备注
							});
						}
					} else {
						uni.showToast({
							title: res.data.msg || '操作失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				});
			},
			handleRightNavClick() {
				// 点击右上角图标，显示操作表
				this.showActionsSheet = true;
			},
			handleActionSelect(action) {
				if (action.name === '设置备注') {
					this.inputRemark = this.currentRemark; // 打开弹窗时，将当前备注填充到输入框
					this.showRemarkModal = true;
				}
				// 可以根据 action.name 处理其他菜单项
			},
			confirmRemark() {
				if (this.inputRemark.trim() === this.currentRemark) {
					this.showRemarkModal = false;
					return; // 如果备注没有改变，则不提交
				}

				let params = {
					friendId: this.userId,
					remark: this.inputRemark.trim()
				};
				uni.showLoading({
					title: '正在提交...'
				});
				setFriendRemark(params).then(res => {
					uni.hideLoading();
					if (res.data && res.data.code === 200) {
						this.currentRemark = this.inputRemark.trim(); // 更新当前页面的备注
						this.showRemarkModal = false;
						uni.showToast({
							title: '备注设置成功',
							icon: 'success'
						});

						// 通知上一个页面备注已更新
						if (this.eventChannel) {
							this.eventChannel.emit('returnData', {
								userId: this.userId,
								type: 5, // 自定义类型，表示备注更新
								remark: this.currentRemark,
								isFollowed: this.isFollowed // 同时回传关注状态，以防万一
							});
						}
					} else {
						uni.showToast({
							title: res.data.msg || '设置失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
				});
			},
			cancelRemark() {
				this.showRemarkModal = false;
				// this.inputRemark = this.currentRemark; // 可选：取消时恢复输入框为当前备注
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F3F3F3;
	}

	.page-content {
		position: relative;
	}

	// NavBar 右侧按钮的样式如果需要自定义，可以在这里添加
	.nav-bar ::v-deep .nav-bar-lr .u-icon {
		/* 假设NavBar内部右侧图标可以通过这个类选择器定位 */
	}
</style>